<template>
  <div class="cmd-web1-container">
    <!-- 头部导航 -->
    <header class="cmd-web1-header">
      <div class="header-content">
        <div class="header-logo-container">
          <i class="fas fa-shield-alt logo-icon"></i>
          <h1 class="site-title">命令执行漏洞练习-随机练习</h1>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="main-content">
      <!-- 关卡信息 -->
      <div class="level-info">
        <div class="level-header">
          <div class="level-icon-container">
            <i class="fas fa-terminal text-xl"></i>
          </div>
          <h2 class="level-title">命令执行漏洞练习 #510</h2>
        </div>
        <p class="level-description">
          本关卡模拟一个存在命令执行漏洞的网络诊断工具。该工具允许用户输入IP地址进行ping测试，但由于缺乏输入验证，存在命令执行漏洞。
        </p>
        <div class="level-objective">
          <p class="objective-title">目标：</p>
          <p>利用命令执行漏洞，获取系统中的FLAG文件（通常位于/flag或/etc/flag）</p>
        </div>
      </div>

      <!-- 靶场模拟区域 -->
      <div class="simulation-container">
        <!-- 左侧：攻击区域 -->
        <div class="attack-area">
          <div class="attack-header">
            <h3 class="attack-title">
              <i class="fas fa-explorer attack-icon"></i>网络诊断工具
            </h3>
          </div>
          <div class="attack-content">
            <p class="attack-description">请输入IP地址进行网络连通性测试：</p>

            <form @submit.prevent="executeCommand" class="attack-form">
              <div class="form-group">
                <input
                    type="text"
                    v-model="userInput"
                    placeholder="例如：192.168.1.1"
                    class="form-input"
                >
                <button
                    type="submit"
                    class="submit-button"
                >
                  <i class="fas fa-play button-icon"></i>执行测试
                </button>
              </div>
            </form>

            <!-- 成功提示信息 -->
            <div v-if="foundFlag" class="success-message">
              <div class="success-content">
                <i class="fas fa-flag-checkered success-icon"></i>
                <h3 class="success-title">攻击成功！</h3>
                <p class="success-text">{{ successMessage }}</p>
                <div class="flag-display">
                  <p class="flag-text">FLAG{Command_1nj3ct10n_1s_d4ng3r0us}</p>
                </div>
                <button @click="resetExercise" class="reset-button">
                  <i class="fas fa-redo"></i> 重新开始练习
                </button>
              </div>
            </div>

            <!-- 执行结果 -->
            <div v-if="!foundFlag" class="result-container">
              <div v-if="loading" class="result-loading">
                <div class="loading-spinner"></div>
              </div>
              <div v-else-if="output.length > 0" class="result-output">
                <div v-for="(line, index) in output" :key="index" :class="getLineClass(line)">
                  {{ line }}
                </div>
              </div>
              <div v-else class="result-empty">
                执行结果将显示在这里...
              </div>
            </div>

            <!-- 新增：探索阶段提示 -->
            <div v-if="discoveryPhase" class="discovery-phase">
              <div class="phase-content">
                <h4 class="phase-title">发现新线索</h4>
                <p class="phase-text">在服务器上发现了一个新路径: http://localhost:8080/new_env/flaw_cmd510/po5645259lnn0.php</p>
                <p class="phase-text">也许你可以在这个新路径上找到更多有用的信息？</p>
                <button @click="visitNewPath" class="phase-button">访问新路径</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：提示和信息 -->
        <div class="info-section">
          <!-- 提示卡片 -->
          <div class="hint-card">
            <h3 class="hint-title">
              <i class="fas fa-lightbulb hint-icon"></i>提示
            </h3>
            <ul class="hint-list">
              <li class="hint-item">
                <i class="fas fa-angle-right hint-item-icon"></i>
                <span>尝试使用命令分隔符，如 ; 或 &&</span>
              </li>
              <li class="hint-item">
                <i class="fas fa-angle-right hint-item-icon"></i>
                <span>在正常命令后添加额外的系统命令</span>
              </li>
              <li class="hint-item">
                <i class="fas fa-angle-right hint-item-icon"></i>
                <span>FLAG可能存储在系统的/flag文件中</span>
              </li>
              <li class="hint-item">
                <i class="fas fa-angle-right hint-item-icon"></i>
                <span>可以尝试使用管道符 | 来组合命令</span>
              </li>
            </ul>
          </div>

          <!-- 状态卡片 -->
          <div class="status-card">
            <h3 class="status-title">
              <i class="fas fa-flag status-icon"></i>任务状态
            </h3>
            <div class="status-list">
              <div class="status-item">
                <span class="status-label">发现命令执行漏洞</span>
                <i :class="foundVulnerability ? 'fas fa-check status-indicator completed' : 'far fa-circle status-indicator'"></i>
              </div>
              <div class="status-item">
                <span class="status-label">成功执行任意命令</span>
                <i :class="executedArbitrary ? 'fas fa-check status-indicator completed' : 'far fa-circle status-indicator'"></i>
              </div>
              <div class="status-item">
                <span class="status-label">获取FLAG</span>
                <i :class="foundFlag ? 'fas fa-check status-indicator completed' : 'far fa-circle status-indicator'"></i>
              </div>
            </div>

            <button
                @click="showSolution = !showSolution"
                class="solution-toggle"
            >
              <i :class="showSolution ? 'fas fa-chevron-up toggle-icon' : 'fas fa-chevron-down toggle-icon'"></i>
              {{ showSolution ? '隐藏攻击路径' : '查看攻击路径' }}
            </button>

            <!-- 解决方案 -->
            <div v-if="showSolution" class="solution-container">
              <h4 class="solution-title">攻击路径：</h4>
              <ol class="solution-steps">
                <li class="solution-step">首先尝试输入正常IP地址，如 <code class="solution-code">127.0.0.1</code>，观察正常输出</li>
                <li class="solution-step">尝试使用命令分隔符注入额外命令，如 <code class="solution-code">127.0.0.1; whoami</code></li>
                <li class="solution-step">确认漏洞存在后，尝试查看flag文件：<code class="solution-code">127.0.0.1; cat /flag</code></li>
                <li class="solution-step">成功获取FLAG：<code class="solution-code solution-flag">FLAG{Command_1nj3ct10n_1s_d4ng3r0us}</code></li>
                <li class="solution-step">也可以尝试使用管道符：<code class="solution-code">127.0.0.1 | grep "pattern"</code></li>
              </ol>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="cmd-web1-footer">
      <div class="footer-content">
        <p class="footer-text">http://localhost:8080/new_env/flaw_cmd1/hjn45521zs8.php</p>
      </div>
    </footer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userInput: '',
      output: [],
      loading: false,
      foundVulnerability: false,
      executedArbitrary: false,
      foundFlag: false,
      showSolution: false,
      attackStage: 0, // 0: initial, 1: vulnerability found, 2: arbitrary command executed, 3: flag found
      successMessage: '', // 存储成功提示信息
      discoveryPhase: false, // 新增：发现阶段
      newPathVisited: false // 新增：是否访问过新路径
    };
  },
  methods: {
    async executeCommand() {
      if (!this.userInput.trim()) {
        this.output = ['错误：请输入IP地址'];
        return;
      }

      this.loading = true;
      this.output = [];

      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 800));

      // 模拟命令执行逻辑
      if (this.userInput.includes(';') || this.userInput.includes('&&') || this.userInput.includes('||')) {
        // 检测到可能的命令注入
        this.foundVulnerability = true;
        this.attackStage = Math.max(this.attackStage, 1);

        // 提取注入的命令
        const injectedCommands = this.userInput.split(/[;|&]+/).slice(1).join('; ');

        // 模拟执行ping命令
        this.output.push(`正在执行: ping -c 4 ${this.userInput.split(/[;|&]+/)[0]}`);
        this.output.push('');
        this.output.push('PING 结果:');
        this.output.push('64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.054 ms');
        this.output.push('64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.078 ms');
        this.output.push('64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.065 ms');
        this.output.push('64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.071 ms');
        this.output.push('');

        // 标记已执行任意命令
        this.executedArbitrary = true;
        this.attackStage = Math.max(this.attackStage, 2);

        // 处理注入的命令
        if (injectedCommands.includes('cat') && (injectedCommands.includes('/flag') || injectedCommands.includes('/etc/flag'))) {
          // 成功获取flag
          this.output.push(`正在执行: ${injectedCommands}`);
          this.output.push('');
          this.output.push('FLAG{Command_1nj3ct10n_1s_d4ng3r0us}');
          this.foundFlag = true;
          this.attackStage = 3;
          this.successMessage = '恭喜！您已成功利用命令执行漏洞并获取FLAG！';
        } else if (injectedCommands.includes('whoami')) {
          this.output.push(`正在执行: ${injectedCommands}`);
          this.output.push('');
          this.output.push('www-data');

          // 新增：在执行whoami命令后触发发现阶段
          if (!this.discoveryPhase) {
            this.discoveryPhase = true;
          }
        } else if (injectedCommands.includes('ls')) {
          this.output.push(`正在执行: ${injectedCommands}`);
          this.output.push('');
          this.output.push('index.php');
          this.output.push('style.css');
          this.output.push('script.js');
          this.output.push('config.php');
          this.output.push('new_env/'); // 新增：显示新路径
        } else if (injectedCommands.includes('pwd')) {
          this.output.push(`正在执行: ${injectedCommands}`);
          this.output.push('');
          this.output.push('/var/www/html');
        } else if (injectedCommands.includes('id')) {
          this.output.push(`正在执行: ${injectedCommands}`);
          this.output.push('');
          this.output.push('uid=33(www-data) gid=33(www-data) groups=33(www-data)');
        } else if (injectedCommands.includes('cat') && injectedCommands.includes('/etc/passwd')) {
          this.output.push(`正在执行: ${injectedCommands}`);
          this.output.push('');
          this.output.push('root:x:0:0:root:/root:/bin/bash');
          this.output.push('daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin');
          this.output.push('bin:x:2:2:bin:/bin:/usr/sbin/nologin');
          this.output.push('www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin');
        } else {
          this.output.push(`正在执行: ${injectedCommands}`);
          this.output.push('');
          this.output.push(`命令 '${injectedCommands}' 执行成功`);
        }
      } else if (this.userInput.includes('|')) {
        // 管道符攻击
        this.foundVulnerability = true;
        this.attackStage = Math.max(this.attackStage, 1);

        const command = this.userInput.split('|')[0].trim();
        const pipedCommand = this.userInput.split('|')[1].trim();

        this.output.push(`正在执行: ${this.userInput}`);
        this.output.push('');
        this.output.push(`PING 结果 (${command}):`);
        this.output.push('64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.054 ms');
        this.output.push('64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.078 ms');
        this.output.push('');

        if (pipedCommand.includes('grep') && pipedCommand.includes('www-data')) {
          this.output.push(`通过管道执行: ${pipedCommand}`);
          this.output.push('');
          this.output.push('www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin');
          this.executedArbitrary = true;
          this.attackStage = Math.max(this.attackStage, 2);

          // 新增：在执行grep命令后触发发现阶段
          if (!this.discoveryPhase) {
            this.discoveryPhase = true;
          }
        } else {
          this.output.push(`管道命令 '${pipedCommand}' 执行完成`);
        }
      } else {
        // 正常的ping命令
        this.output.push(`正在执行: ping -c 4 ${this.userInput}`);
        this.output.push('');
        this.output.push('PING 结果:');
        this.output.push(`64 bytes from ${this.userInput}: icmp_seq=1 ttl=64 time=0.054 ms`);
        this.output.push(`64 bytes from ${this.userInput}: icmp_seq=2 ttl=64 time=0.078 ms`);
        this.output.push(`64 bytes from ${this.userInput}: icmp_seq=3 ttl=64 time=0.065 ms`);
        this.output.push(`64 bytes from ${this.userInput}: icmp_seq=4 ttl=64 time=0.071 ms`);
        this.output.push('');
        this.output.push(`--- ${this.userInput} ping statistics ---`);
        this.output.push('4 packets transmitted, 4 received, 0% packet loss, time 3072ms');
      }

      this.loading = false;
    },
    getLineClass(line) {
      if (line.includes('FLAG{')) {
        return 'output-flag';
      } else if (line.startsWith('正在执行:')) {
        return 'output-command';
      } else if (line.includes('错误：')) {
        return 'output-error';
      }
      return '';
    },
    resetExercise() {
      this.userInput = '';
      this.output = [];
      this.foundVulnerability = false;
      this.executedArbitrary = false;
      this.foundFlag = false;
      this.attackStage = 0;
      this.successMessage = '';
      this.discoveryPhase = false;
      this.newPathVisited = false;
    },
    // 新增方法：访问新路径
    visitNewPath() {
      this.newPathVisited = true;
      this.output = [];
      this.output.push('正在访问: http://localhost:8080/new_env/flaw_cmd510/po5645259lnn0.php');
      this.output.push('');
      this.output.push('HTTP/1.1 200 OK');
      this.output.push('Content-Type: text/html');
      this.output.push('');
      this.output.push('<html>');
      this.output.push('<head><title>Secret Directory</title></head>');
      this.output.push('<body>');
      this.output.push('  <h1>Secret Directory</h1>');
      this.output.push('  <p>Welcome to the secret directory!</p>');
      this.output.push('  <p>You have successfully found the hidden path.</p>');
      this.output.push('  <p>Here is a hint for you: The flag is not here, but you can find it in the /flag file.</p>');
      this.output.push('  <p>Try to use command injection to read the flag file.</p>');
      this.output.push('</body>');
      this.output.push('</html>');
      this.output.push('');
      this.output.push('访问完成。');

      // 隐藏发现阶段提示
      this.discoveryPhase = false;
    }
  }
};
</script>

<style scoped lang="css" src="@/assets/styles/cmdweb1.css"></style>